Exercise

  1. Combine all elements of df_list to one data frame. The result should be only a single line of code.
  1. Fix each of the following common data frame subsetting errors:
  1. What does df[is.na(df)] <- 0 do
  1. How would you randomly permute the columns of a data frame?
  1. Write a while and a repeat loop doing the same as
for(i in LETTERS[1:10]){
  print(i)
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# while 
i <- 0
while (i < 10) {
  i = i + 1
  print(LETTERS[i])
  
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# alternative 
i <- 1
while (i < 11) {
  print(LETTERS[i])
  i = i + 1 
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# repeat
i <- 0
repeat{
  i = i + 1
  print(LETTERS[i])
  if (i > 9) {
    break
  }
  
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# alternative
i <- 1
repeat{
  print(LETTERS[i])
  i = i + 1 
  if (i > 10) {
    break
  }
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
  1. Write a for loop doing the same as
count <- 0
repeat{
  x     <- sample(1:6, 1)
  count <- count + 1 
  if(x == 6) break
}
print(count)
## [1] 21
for (i in 1:100) {
  x     <- sample(1:6, 1)
  count <- i
  if(x == 6) break
}
print(count)
## [1] 6
  1. What is the problem here?
  1. What is the problem here? Can you debug it?
df <- mtcars

lin_mod <- function(df){
lm(y ~ . ,data = df)
}

simple_lin_mod <- function(data, y, x){
df <- data[ ,c(y, x)]
names(df) <- c("y", "x")
lin_mod(df)
}

simple_lin_mod(df, "mpg", "cyl")
## 
## Call:
## lm(formula = y ~ ., data = df)
## 
## Coefficients:
## (Intercept)            x  
##      37.885       -2.876